package com.example.erat.controller;

import com.example.erat.dto.ClassDTO;
import com.example.erat.dto.ResponseResult;
import com.example.erat.dto.StudentDTO;
import com.example.erat.service.ClassService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.List;

/**
 * 班级控制器
 */
@RestController
@RequestMapping("/api/classes")
public class ClassController {

    @Autowired
    private ClassService classService;

    /**
     * 创建班级
     */
    @PostMapping
    public ResponseResult<ClassDTO> createClass(@Valid @RequestBody ClassDTO classDTO) {
        return ResponseResult.success(classService.createClass(classDTO));
    }

    /**
     * 更新班级
     */
    @PutMapping("/{id}")
    public ResponseResult<ClassDTO> updateClass(@PathVariable Long id, @Valid @RequestBody ClassDTO classDTO) {
        classDTO.setId(id);
        return ResponseResult.success(classService.updateClass(classDTO));
    }

    /**
     * 删除班级
     */
    @DeleteMapping("/{id}")
    public ResponseResult<Void> deleteClass(@PathVariable Long id) {
        classService.deleteClass(id);
        return ResponseResult.success();
    }

    /**
     * 获取班级详情
     */
    @GetMapping("/{id}")
    public ResponseResult<ClassDTO> getClass(@PathVariable Long id) {
        return ResponseResult.success(classService.getClassById(id));
    }

    /**
     * 获取班级列表
     */
    @GetMapping
    public ResponseResult<List<ClassDTO>> listClasses() {
        return ResponseResult.success(classService.listClasses());
    }

    /**
     * 导入学生
     */
    @PostMapping(value = "/{id}/students/import", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseResult<List<StudentDTO>> importStudents(@PathVariable Long id, @RequestParam("file") MultipartFile file) {
        return ResponseResult.success(classService.importStudents(id, file));
    }

    /**
     * 添加学生
     */
    @PostMapping("/{id}/students")
    public ResponseResult<StudentDTO> addStudent(@PathVariable Long id, @Valid @RequestBody StudentDTO studentDTO) {
        return ResponseResult.success(classService.addStudent(id, studentDTO));
    }

    /**
     * 删除学生
     */
    @DeleteMapping("/{classId}/students/{studentId}")
    public ResponseResult<Void> removeStudent(@PathVariable Long classId, @PathVariable Long studentId) {
        classService.removeStudent(classId, studentId);
        return ResponseResult.success();
    }

    /**
     * 获取班级学生列表
     */
    @GetMapping("/{id}/students")
    public ResponseResult<List<StudentDTO>> listClassStudents(@PathVariable Long id) {
        return ResponseResult.success(classService.listClassStudents(id));
    }
} 